<template>
    <div class="app-container" v-loading="loading">
        <levelbar></levelbar>
        <el-form label-width="80px" class="app-content form-box" :rules="rules"
        :model="formInline" ref="formInline">
            <div class="box">
                <div class="tea-infor">
                    <div class="form-title">{{title}}</div>
                    <div class="form-item">
                         <div class="form-item-title">
                            <span class="title-level">标题与发布者</span>
                        </div>
                        <div class="form-content">
                          <el-row :gutter="20">
                            <el-col :span="9">
                                <el-form-item label="标题" prop="title">
                                     <el-popover placement="top-start" trigger="focus" content="字符长度不大于28位">
                                       <el-input v-model="formInline.title" placeholder="请输入标题" :maxlength="28" slot="reference"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                            <el-col :span="9">
                                <el-form-item label="类别" prop="type">
                                    <el-select v-model="formInline.type" placeholder="请选择" style="width:100%;" >
                                        <el-option v-for="(item,index) in formInline.typeArr" :key="index" :label="item.type" 
                                        :value="item.id"></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                          </el-row>
                           <el-row :gutter="20">
                            <el-col :span="9">
                                <el-form-item label="发布者" prop="createPeople">
                                     <el-popover placement="top-start" trigger="focus" content="字符长度不大于10位">
                                       <el-input v-model="formInline.createPeople" placeholder="请输入发布者" :maxlength="10" slot="reference"></el-input>
                                    </el-popover>
                                </el-form-item>
                            </el-col>
                          </el-row>
                    </div>
                    </div>
                </div>
                <div class="form-item">
                     <div class="form-item-title">
                        <span class="title-level">封面</span>
                     </div>
                    <div class="form-content">
                     <div class="form-item">
                            <div class="uploadImg">
                                <span >&nbsp;&nbsp;<font color="red">*</font>上传封面
                                    <span class="warn-title">(支持 JPG PNG GIF 格式，200KB以内、比例3:4的图片！)</span>
                                </span>
                            </div>
                            <div class="form-content">
                                <el-row :gutter="41">
                                    <el-col :span="24" class="upload-image">
                                          <div class="img-box">
                                                <el-form-item label="">
                                                    <fileUpload 
                                                    ref="fileUpload"
                                                    @remove="fileImgRemove" 
                                                    :img-size="0.1953125"
                                                    :isMultiple="imgOptions.isMultiple"
                                                    :file-list.sync="imgOptions.fileList" 
                                                    :file-list-show.sync="imgOptions.fileListShow" 
                                                    :list-type="imgOptions.listType"
                                                    :up-file-type="imgOptions.upFileType"
                                                    :accept-list="imgOptions.accept"
                                                    @onSuccess="onSuccess"
                                                    >
                                                    <i class="el-icon-plus avatar-uploader-icon"></i>
                                                </fileUpload>
                                                </el-form-item>
                                          </div>
                                    </el-col>
                                </el-row>
                            </div>
                        </div>
                    </div>
                </div>
                 <div class="form-item">
                         <div class="form-item-title">
                            <span class="title-level">文章正文</span>
                        </div>
                        <div class="form-content">
                            <el-row :gutter="41">
                                <el-col :span="21" class="radio">
                                    <el-radio-group v-model="formInline.showType">
                                        <el-radio  label="0">链接</el-radio>
                                        <el-radio  label="1">自定义</el-radio>
                                    </el-radio-group>
                                    <div class="link-box">
                                        <div class="box" v-if="formInline.showType === '0'">
                                            <el-form-item label-width="0" prop="link">
                                                <el-popover  placement="top-start" trigger="focus" content="请输入http://或https://前缀链接">
                                                    <el-input slot="reference" :maxlength="100" v-model="formInline.link" placeholder="请输入链接" style="width:46%"></el-input>
                                                </el-popover>
                                            </el-form-item>
                                        </div>
                                        <div v-if="formInline.showType === '1'">
                                            <el-form-item>
                                                <Tinymce :id="tinymceId" :height="260" ref="formInline.content"
                                                 v-model="formInline.html"></Tinymce>
                                            </el-form-item>
                                        </div>
                                    </div>
                                </el-col>
                           </el-row>
                         </div>
                 </div>
                 <div class="form-item">
                    <el-row>
                        <el-col :span="24">
                            <div class="footer">
                              <el-button @click="resetForm('formInline')">取消</el-button>
                              <el-button type="primary" @click="submitForm('formInline')">发布</el-button>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </div>
        </el-form>
    </div>
</template>
<script>
import Levelbar from '../layout/Levelbar';
import Tinymce from 'components/Tinymce';
import fileUpload from 'components/Upload/fileUpload';
import { mapGetters } from 'vuex';
import { createArticle, editType, editArticle, editButton} from 'api/eschool';
export default {
    name: 'correct',
    components: { Levelbar, fileUpload, Tinymce},
    data() {
        var link = (rule, value, callback) => {
            if (this.formInline.showType === '0') {// 如果选择的是链接
                if (value === '') {
                    callback(new Error('请输入链接'));
                } else {
                    callback();
                }
            }
        };
       
        return {
            type:'',//记录该页面进来时的 类别
            title: '',
            loading: true,
            tinymceId: 'tinymceId',
            imgUrl: '',
            imgOptions: {
                upFileType: 'image',
                fileListShow: true,
                fileList: [],
                isMultiple: false,
                imageInfor: [],
                fileListMaxLen: false // 是否达最大上传量(控制添加按钮显示)
            },
            formInline: {
                content: '',
                html: '',
                title: '', // 标题
                type: '', // 类别
                createPeople: '', // 发布者
                link: '',
                showType: '0',
                typeArr: [] // 编辑分类
            },
            rules: {
                
                title: [
                      { required: true, message: '请输入标题'},
                      { pattern: /^[^\s]+$/, message: '请勿输入空格', trigger: 'blur' }
                ],
                type: [
                     { required: true, message: '请选择类别'}
                ],
                // 发布者
                createPeople: [
                      { pattern: /^[^\s]+$/, message: '请勿输入空格', trigger: 'blur' }
                ],
                link: [
                    { pattern: /^(https?):\/\/\w*\.\w*/, message: '请输入合法的链接' },
                    { validator: link, trigger: 'blur' }
                ]
            }
        }
    },
    created() {
        // this.schoolType=this.$route.params.schoolType;
        this.editType();
        this.editOrNewAdd();// 判断是编辑还是新建
        
    },
    computed: {
        ...mapGetters([
            'uid',
            'schoolId',
            'schoolName'
        ])
    },
    methods: {
   
        // 获取已有的编辑分类
        editType() {
            editType(this.schoolId).then(res => {
                this.formInline.typeArr=res.data.content;
                this.formInline.typeArr.unshift({id: '', type: '请选择'})
            })
        },
        // 判断是编辑还是新建
        editOrNewAdd() {
            if (this.$route.params.status=='2') {// 编辑
                this.title='编辑文章';
                editButton(this.$route.params.id).then(res => {
                    this.loading=false;
                    let data=res.data.content;
                    this.formInline.title=data.sName;
                    this.type=data.fTypeId;//记录回填时候的类别 点击发布时 判断是不是修改了 类别
                    this.formInline.type=data.fTypeId;
                    this.formInline.showType=data.sShowType;
                    this.formInline.html=data.sHtml;
                    this.formInline.link=data.sLink;
                    this.formInline.createPeople=data.sPublisher;
                    this.imgUrl=data.sPic;
                    this.imgOptions.fileList.push({name: '', url: data.sPic});
                }).catch(() => {
                    this.loading=false;
                })
            } else {
                this.title='新建文章';
                this.loading=false;
            }
        },
     // 移除图片
        fileImgRemove() {
            this.imgUrl= ''
        },
         // 上传图片成功后获取图片路径
        onSuccess(data) {
            this.imgUrl= data.imgUrl;// 发给后台的src 数组
        },
        submitForm(formInline) {
            this.$refs[formInline].validate((valid) => {
                if (valid) {
                    if (!this.imgUrl) {
                        this.$message.info('请先上传封面');
                        return;
                    }
                    if (this.formInline.showType === '1') {// 选择的自定义 就要输入自定义内容
                        let tempHtml = window.tinymce.get('tinymceId').getContent({format: 'raw'});
                        if (tempHtml.indexOf('img') === -1) {
                            if (!window.tinymce.get('tinymceId').getContent({format: 'text'}).trim()) {
                                this.$message.info('请输入自定义内容');
                                return false;
                            }
                            if (window.tinymce.get('tinymceId').getContent({format: 'text'}).trim().length > 10000) {
                                this.$message.info('自定义内容字数不得大于10000字');
                                return false;
                            }
                        }
                    }
                    this.$confirm(`确定要${this.title}吗?`, ' ', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消'
                    }).then(() => {
                        this.loading=true;
                        if (this.$route.params.status=='1') {// 新建
                            this.createArticle();
                        } else {// 编辑
                            if(this.type!=this.formInline.type){//证明更改了所属类别
                                this.$alert('您已更改本文章的所属类别，记得及时更新在e校园“框架设置”中的链接哟~', ' ', {
                                    confirmButtonText: '知道了',
                                    callback: action => {
                                        //console.log()
                                    }
                                });
                            }
                            this.editArticle();
                        }
                    });
                } else {
                    return false;
                }
            });
        },
        // 新建文章
        createArticle() {
            let schoolId=this.schoolId, // 学校id
                title=this.formInline.title, // 标题
                typeId=this.formInline.type, // 类型id
                showType=this.formInline.showType, // 展现形式
                html=this.formInline.html, // html源码
                pic=this.imgUrl, // 封面图片
                creator=this.uid, // 创建人
                publisher=this.formInline.createPeople, // 发布人
                link=this.formInline.link;
            createArticle(schoolId, title, typeId, showType, html, pic, creator, publisher, link).then(res => {
                this.loading=false;
                this.$router.go(-1)
                this.$store.dispatch('UpdateCache'); // 刷新
            }).catch(() => {
                this.loading=false;
            })
        },
        // 编辑文章
        editArticle() {
            let schoolId=this.schoolId, // 学校id
                articleId=this.$route.params.id,
                title=this.formInline.title, // 标题
                typeId=this.formInline.type, // 类型id
                showType=this.formInline.showType, // 展现形式
                html=this.formInline.html, // html源码
                pic=this.imgUrl, // 封面图片
                creator=this.uid, // 创建人
                publisher=this.formInline.createPeople, // 发布人
                link=this.formInline.link;
            editArticle(schoolId, articleId, title, typeId, showType, html, pic, creator, publisher, link).then(res => {
                this.loading=false;
                this.$router.go(-1)
                this.$store.dispatch('UpdateCache'); // 刷新
            }).catch(() => {
                this.loading=false;
            })
        },
        // 重置
        resetForm(dataForm) {
            this.$router.go(-1)
        }
    }
}
</script>

<style lang="scss" scoped>
$bgcolor: #fff;

 @mixin showTitle() {
            background: $bgcolor;
            box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
           -webkit-box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.1);
}
.app-container {
    position: relative;
    padding: 20px 20px 10px;
    .app-levelbar {
        height: 35px;
    }
    .el-form {
       .form-item-title {
            margin: 40px 0;
            font-size: 14px;
            color: #333;
            line-height: 14px;
            border-left: 4px solid #ff5e2c;
            text-indent: 16px;
        }
    }
    
}
.form-box {
        padding: 0px 50px 0;
        @include showTitle();
        .form-item {
        padding-bottom: 40px;
        }
        .form-title {
           padding-top:8px;
            text-align: center;
            font-size: 18px;
            color: #333;
            line-height: 72px;
            font-weight: bold;
            font-family: Microsoft YaHei;
            border-bottom: 1px solid #ddd;
        }
        .footer {
            text-align: center;
            margin-top: 40px;
        }
}
.uploadImg 
{
    margin-bottom:30px;
    span{
       font-size: 14px;
       color: #333;
       padding-left:6px;
      
    }
}
.link-box{
    margin-top:20px;
}
</style>
